﻿using NewLife.Data;
using NewLife.Model;
using NewLife.Net;
using System;
using System.Collections.Generic;
using System.Text;

namespace TK.Socket
{
    /// <summary>
    /// 数据处理
    /// </summary>
    public class DataHandler : Handler
    {
        private readonly IReceiveDataHandler _receiveData;

        /// <summary>
        /// ctor
        /// </summary>
        public DataHandler(IReceiveDataHandler receiveData)
        {
            _receiveData = receiveData;
        }

        /// <summary>
        /// 读取数据
        /// </summary>
        public override object Read(IHandlerContext context, object message)
        {
            var ctx = context as NetHandlerContext;
            if (message is Packet packet)
            {
                var data = new DataPacket
                {
                    DataType = DataType.Receive,
                    Server = ctx.Session.Local.ToString(),
                    Client = ctx.Session.Remote.ToString(),
                    Data = packet.ToArray()
                };
                if (_receiveData != null)
                {
                    _receiveData.ReceiveData(data);
                }
            }
            else
            {
                ctx.Session.WriteLog("message is not Packet type");
            }

            return null;
        }
    }
}
